package com.mayisoftware.mayioa.business.pool.impl.controller;

import com.mayisoftware.mayioa.business.pool.api.domain.PoolMgrInfo;
import com.mayisoftware.mayioa.business.pool.api.service.IPoolManualService;
import com.mayisoftware.mayioa.common.api.annotation.Log;
import com.mayisoftware.mayioa.common.api.base.AjaxResult;
import com.mayisoftware.mayioa.common.api.enums.BusinessType;
import com.mayisoftware.mayioa.common.impl.support.Convert;
import com.mayisoftware.mayioa.common.impl.utils.ExcelUtil;
import com.mayisoftware.mayioa.common.impl.utils.StringUtils;
import com.mayisoftware.mayioa.platform.api.domain.SysRole;
import com.mayisoftware.mayioa.platform.api.domain.SysRoleDept;
import com.mayisoftware.mayioa.platform.api.domain.SysUser;
import com.mayisoftware.mayioa.platform.api.service.ISysRoleService;
import com.mayisoftware.mayioa.platform.api.service.ISysUserService;
import com.mayisoftware.mayioa.platform.impl.util.ShiroUtils;
import com.mayisoftware.mayioa.platform.impl.web.base.BaseController;
import com.mayisoftware.mayioa.platform.impl.web.page.TableDataInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import  com.mayisoftware.mayioa.business.pool.api.domain.PoolConstants;


@Controller
@RequestMapping("/pool/manual")
public class PoolManualController extends BaseController{

    /**
     * 用户服务
     */
    @Autowired
    ISysUserService sysUserService;

    /**
     * 角色服务
     */
    @Autowired
    ISysRoleService sysRoleService;
    /**
     * 骨干池管理服务注入
     */
    @Autowired
    IPoolManualService poolManualService;

    /**
     * 前缀
     */
    private String prefix = "pool/manual";

    @RequiresPermissions("pool:manual:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/manual";
    }

    @RequiresPermissions("pool:manual:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PoolMgrInfo record)
    {
        startPage();
        List<PoolMgrInfo> list = poolManualService.queryPoolList(record);
        return getDataTable(list);
    }



    @Log(title = "导出骨干信息", businessType = BusinessType.EXPORT)
    @RequiresPermissions("pool:manual:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PoolMgrInfo info)
    {
        List<PoolMgrInfo> list = poolManualService.queryPoolList(info);
        ExcelUtil<PoolMgrInfo> util = new ExcelUtil<PoolMgrInfo>(PoolMgrInfo.class);
        return util.exportExcel(list, "骨干信息");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        return prefix + "/add";
    }

    /**
     * 新增骨干信息
     */
    @RequiresPermissions("pool:manual:add")
    @Log(title = "新增骨干信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(PoolMgrInfo info)
    {
        if (StringUtils.isNotNull(info.getPoolUserId()) && SysUser.isAdmin(info.getPoolUserId().longValue()))
        {
            return error("不允许修改超级管理员用户");
        }

        if(info.getPoolUserId() == null  ){
            return error("手动加入骨干池不能不填写用户ID");
        }

        if(StringUtils.isEmpty(info.getPoolInDesc()) ){
            return error("手动加入骨干池不能不填写原因");
        }

        SysUser userInfo =sysUserService.selectUserById(info.getPoolUserId().longValue());

        if(userInfo ==null){
            return  error("该用户不存在");
        }

        SysUser curUser = ShiroUtils.getSysUser();

        List<SysRole> curRoles = curUser.getRoles();
        boolean bfind = false;
        for (SysRole sysRole:curRoles){
            if (!StringUtils.isEmpty(sysRole.getDataScope()) &&sysRole.getDataScope().equalsIgnoreCase("1") ){
                bfind = true;
                break;
            }
            else {
                List<SysRoleDept> tmpDepts = sysRoleService.selectDeptsByRole(sysRole.getRoleId());

                for (SysRoleDept sysRoleDept: tmpDepts){
                    if (sysRoleDept.getDeptId()!= null &&userInfo.getDept() != null &&sysRoleDept.equals(userInfo.getDept().getDeptId())){
                        bfind =true;
                        break;
                    }
                }
            }
        }

        if (!bfind){
            return error("没有权限添加该用户");
        }


        List<PoolMgrInfo>  backInfo = poolManualService.queryPoolListByUserId(info.getPoolUserId()+"");

        if(!CollectionUtils.isEmpty(backInfo)){
            for (PoolMgrInfo tmpInfo:backInfo) {
                if (tmpInfo.getPoolIsBackbone().equals(PoolConstants.IS_BACKBONE)){
                    return error("已经是骨干了");
                }

                if (tmpInfo.getPoolCreateType().equals(PoolConstants.CREATE_TYPE_MUL)){
                    return error("已经是添加过，请编辑");
                }
            }
        }

        info.setPoolIsBackbone(PoolConstants.IS_BACKBONE);
        info.setPoolCreateType(PoolConstants.CREATE_TYPE_MUL);
        info.setPoolInTime(new Date());
        info.setPoolUpdateUserId(ShiroUtils.getUserId().intValue());

        return toAjax(poolManualService.addPoolInfo(info));
    }

    /**
     * 修改骨干信息
     */
    @GetMapping("/edit/{poolRecordId}")
    public String edit(@PathVariable("poolRecordId") Long poolRecordId, ModelMap mmap)
    {
        mmap.put("poolInfo", poolManualService.queryPoolListById(poolRecordId+"").get(0));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("pool:manual:edit")
    @Log(title = "配置骨干用户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editSave(PoolMgrInfo info)
    {
        if (StringUtils.isNotNull(info.getPoolUserId()) && SysUser.isAdmin(info.getPoolUserId().longValue()))
        {
            return error("不允许修改超级管理员用户");
        }

        if(info.getPoolUserId() == null  ){
            return error("手动配置骨干池不能不填写用户ID");
        }

        SysUser userInfo =sysUserService.selectUserById(info.getPoolUserId().longValue());

        if(userInfo ==null || info.getPoolIsBackbone() == null){
            return  error("该用户不存在");
        }

        if (info.getPoolIsBackbone().equals(PoolConstants.IS_BACKBONE) ){
            if(StringUtils.isEmpty(info.getPoolInDesc())){
                return error("配置骨干需要输入加入原因");
            }
            else {
                info.setPoolInTime(new Date());
                info.setPoolCreateType(PoolConstants.CREATE_TYPE_MUL);
            }
        }

        if (info.getPoolIsBackbone().equals(PoolConstants.NOT_BACKBONE) ){
            if(StringUtils.isEmpty(info.getPoolOutDesc())){
                return error("剔除骨干需要输入剔除原因");
            }
            else {
                info.setPoolOutTime(new Date());
                info.setPoolDeleteType(PoolConstants.DELETE_TYPE_MUL);
            }
        }

        return toAjax(poolManualService.modifyPoolInfo(info));
    }


    /**
     * 修改保存用户
     */
    @RequiresPermissions("pool:manual:recalculate")
    @Log(title = "全部重新计算", businessType = BusinessType.CLEAN)
    @PostMapping("/recalculate")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult recalculate()
    {
        return toAjax(poolManualService.modifyPoolInfoToCacl());
    }

    @RequiresPermissions("pool:manual:remove")
    @Log(title = "删除骨干信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        try
        {
            if (StringUtils.isEmpty(ids)){
                return  error("请输入id信息");
            }

            Integer[] recordIds = null;

            try{
                recordIds= Convert.toIntArray(ids);
            }
            catch (Exception e){
                return  error("id必须为数字");
            }


            return toAjax(poolManualService.rmvPoolByIds(recordIds));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }


}
